package com.example.demo1.mapper;

import com.example.demo1.entity.User;
import com.example.demo1.util.StringUtil;

import java.util.ArrayList;

public class UserMapperProvider {
        public String getUpdateUserSql(User user){
            StringBuffer sql = new StringBuffer("UPDATE user SET ");
            ArrayList<String> fieldList = new ArrayList<>();

            // 收集所有待更新的字段
            if (StringUtil.isNotEmpty(user.getPswd())) {
                fieldList.add("pswd = #{pswd}");
            }

            if (StringUtil.isNotEmpty(user.getUser_nickname())) {
                fieldList.add("user_nickname = #{user_nickname}");
            }

            if (StringUtil.isNotEmpty(user.getUser_identity())) {
                fieldList.add("user_identity = #{user_identity}");
            }

            if (StringUtil.isNotEmpty(user.getUser_sex())) {
                fieldList.add("user_sex = #{user_sex}");
            }

            if (StringUtil.isNotEmpty(user.getUser_picture())) {
                fieldList.add("user_picture = #{user_picture}");
            }

            if (StringUtil.isNotEmpty(user.getUser_phnum())) {
                fieldList.add("user_phnum = #{user_phnum}");
            }

            if (StringUtil.isNotEmpty(user.getUser_email())) {
                fieldList.add("user_email = #{user_email}");
            }

            // 如果没有需要更新的字段，直接返回
            if (fieldList.isEmpty()) {
                System.out.println("无更新字段");
                return null;
            }

            // 使用逗号和空格连接所有字段，确保无多余逗号
            String setClause = String.join(", ", fieldList);
            sql.append(setClause);
            sql.append(" WHERE user_id = #{user_id}");

            return sql.toString();
        }

        public String getSelectUsersSql(User user){
            StringBuffer sql = new StringBuffer( "select * from user where 1=1");
            ArrayList<Object> params = new ArrayList<>();
            if(StringUtil.isNotEmpty(user.getUser_id())){
                sql.append(" and user_id = #{user_id}");
            }
            if(StringUtil.isNotEmpty(user.getUser_name())){
                sql.append(" and user_name like concat('%',#{user_name},'%')");
            }

            if(StringUtil.isNotEmpty(user.getUser_identity())){
                sql.append(" and user_identity = #{user_identity}");
            }
            if(StringUtil.isNotEmpty(user.getUser_sex())){
                sql.append(" and user_sex = #{user_sex}");
            }
            if(StringUtil.isNotEmpty(user.getUser_phnum())){
                sql.append(" and user_phnum like concat('%',#{user_phnum},'%')");
            }
            if(StringUtil.isNotEmpty(user.getUser_email())){
                sql.append(" and user_email like concat('%',#{user_email},'%')");
            }
            return sql.toString();
        }
}
